<template>
  <el-container v-loading="loading" class="container">
    <el-form ref="form" :rules="rules" label-position="left" label-width="120px" :model="form" style="width:60%">
      <el-form-item label="行业名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入行业名称" maxlength="15" type="text" show-word-limit/>
      </el-form-item>
      <el-form-item label="行业说明" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入行业说明" maxlength="500" show-word-limit rows="4"/>
      </el-form-item>
      <el-form-item label="行业权限" prop="bizFeatures">
        <el-checkbox-group v-model="form.bizFeatures" :disabled="form.allFeatures">
          <el-checkbox v-for="item in baseBizFeatures" :key="item.id" :label="item.id" @click.native="onClick">{{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="form.allFeatures" @change="handleAllFeaturesChange">全部功能</el-checkbox>
      </el-form-item>
      <el-form-item label="行业状态" prop="status">
        <el-radio-group v-model="form.status" :disabled="useCountBuer">
          <el-radio :label="1">不启用</el-radio>
          <el-radio :label="0">启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">返回</el-button>
      </el-form-item>
    </el-form>
  </el-container>
</template>

<script>
import { allAuth,addBusiness,updateBusiness,ownerAuth} from '@/api/business'
export default {
  components: {
  },
  props: {
    mode: '',
    id:'',
  },
  data() {
    const validatorBizFeatures = (rule, value = '', callback) => {
      if (!this.form.allFeatures && this.form.bizFeatures.length == 0) {
        callback(new Error('请勾选行业权限'))
      } else {
        callback()
      }
    }
    return {
      form: {
        allFeatures: false,
        bizFeatures: [],
        description: null,
        name: null,
        status:1
      },
      // 状态
      loading: false,
      useCountBuer:false,
      oldBizFeatures: [],
      baseBizFeatures:[],
      rules: {
        name: [{
          min: 1,
          max: 15,
          required: true,
          message: '请输入行业名称, 长度在 1 ~ 15 个字符',
          trigger: 'blur'
        }
        ],
        description: [{
          min: 1,
          max: 500,
          required: true,
          message: '请输入行业说明, 长度在 1 ~ 500 个字符',
          trigger: 'blur'
        }
        ],
        status: [{
          required: true
        }
        ],
        bizFeatures: [{ required: true, validator: validatorBizFeatures, trigger: ['blur', 'change'] }],
      },
      loading: false,
    }
  },
  mounted() {
    console.log('mode',this.mode)
    console.log('id',this.id)
    this.getSpPackageFeatures()
    if(this.mode==='edit'){
    this.getOwnerAuth(this.id)
    }
  },
  methods: {
    onClick(){
      console.log('aaaa')
    },
    // 获取全部权限
    getSpPackageFeatures() {
      new Promise((resolve, reject) => {
        this.loading = true
        allAuth().then(res => {
          console.log('11',res.data)
          this.baseBizFeatures = res.data
          resolve()
        }).finally(() => {
          this.loading = false
          resolve()
        })
      })
    },
    getOwnerAuth(id){
       new Promise((resolve, reject) => {
        this.loading = true
        ownerAuth({bizPackageId:id}).then(res => {
          console.log('22',res.data)
          this.useCountBuer = res.data.useCount > 0 ? true : false
          this.form.name=res.data.name
          this.form.description=res.data.description
          this.form.status=res.data.status
          if (res.data.allFeatures) {
            this.form.allFeatures = res.data.allFeatures
            this.form.bizFeatures = this.baseBizFeatures.map(item => {
              return item.id
            })
            this.oldBizFeatures = this.baseBizFeatures.map(item => {
              return item.id
            })
            // this.$forceUpdate()
          }else{
             this.form.bizFeatures = res.data.features ? res.data.features.split(',').map(Number) : []
             this.oldBizFeatures = res.data.features ? res.data.features.split(',').map(Number) : []
          }
          resolve()
        }).finally(() => {
          this.loading = false
          resolve()
        })
      })
    },
     // 全部功能
    handleAllFeaturesChange(val) {
      console.log('wwww',val)
      if (val) {
        const bizFeatures = this.baseBizFeatures.map(item => {
          return item.id
        })
        this.$set(this.form, 'bizFeatures', bizFeatures)
      }
    },
    handleCancel() {
      this.$emit('cancel')
    },
    interface(){
      const params = JSON.parse(JSON.stringify(this.form))
          if (params.allFeatures) {
            params.bizFeatures = []
          }
           params.features = params.bizFeatures.join(',')
          let apiFun = null
          if (this.mode === 'add') {
            apiFun = addBusiness
          } else {
            apiFun = updateBusiness
            params.id =this.id
          }
        apiFun(params).then(res => {
            this.$notify({
              title: '成功',
              message: this.mode === 'add' ? '新增成功' : '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.$emit('cancel')
          }).finally(() => {
            this.loading = false
          })
    },
    handleSubmit() {
      console.log('this.form.bizFeatures',this.form.bizFeatures)
      console.log('this.oldBizFeatures',this.oldBizFeatures)
      this.$refs.form.validate(valid => {
      if (valid) {
      let c = []
      this.oldBizFeatures.forEach(item => {
       if(this.oldBizFeatures.includes(item)&&!this.form.bizFeatures.includes(item)) {
       c.push(item)
      }
      })
      console.log('cccc',c)
        if(c.length>0 && this.useCountBuer){
        this.$confirm('菜单已有商户在使用，取消菜单会导致商户不能正常使用，请谨慎操作。', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.interface()
      })
       }else{
        this.$confirm(this.form.status==1?'当前行业状态为“未启用”，是否继续保存行业?':'当前行业状态为“已启用”，保存后代理可按照行业增加商户，不可删除，请谨慎操作。', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.interface()
      })
       }
          // this.$emit('submit', data)
        }
      })
    },
    /**
     * 方法组
     */
    //  格式化
    parseFeatures(featureStr) {
      if (!featureStr) {
        return []
      }
      const features = featureStr.split(',')
      return features.map(item => {
        return Number(item)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

/deep/.el-checkbox__input.is-checked + .el-checkbox__label{
    color:#ffb72f
}

// /deep/.el-checkbox__input.is-indeterminate .el-checkbox__inner{
//   background-color: #ffb72f;
//   border-color: #ffb72f
// }
</style>
